// pages/admin/login/index.js
const cloudHelper = require("../../../helper/cloud_helper.js");
const cacheHelper = require('../../../helper/cache_helper.js');
const constants = require('../../../setting/constants.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        name: '',
        pwd: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 记住密码 
        let cacheData = cacheHelper.get('admin-pwd');
        if (cacheData) {
            this.setData({
                name: cacheData.name,
                pwd: cacheData.pwd
            });
        }
    },

    // 点击登陆
    async bindLoad() {
        let name = this.data.name;
        let pwd = this.data.pwd;
        if (!name) {
            wx.showToast({
                title: '请输入账号',
                icon: 'error',
            })
            return;
        }
        if (!pwd) {
            wx.showToast({
                title: '请输入密码',
                icon: 'error',
            })
            return;
        }
        let params = {
            name,
            pwd
        };
        let res = await cloudHelper.callCloudData('api/admin/login', params);
        if (res && res.name) {
            // 记住密码
            cacheHelper.set('admin-pwd', {
                pwd: this.data.pwd,
                name: this.data.name
            }, 86400 * 30);
            // 登陆成功
            cacheHelper.set(constants.CACHE_ADMIN, res, constants.ADMIN_TOKEN_EXPIRE);
            wx.reLaunch({
                url: '/pages/admin/home/index',
            })
        } else {
            wx.showToast({
                title: '登陆失败',
                icon: 'error',
            })
        }
    }
})